using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using Fulan.OutlookSyn.Objects;

namespace Fulan.OutlookSyn.Helper
{
    public class SettingInfoHelper
    {
        private static readonly string infoFile="setting.xml";
        public static void SaveInfo(SettingInfo info)
        {
            XmlSerializer ser = new XmlSerializer(typeof(SettingInfo));
            FileStream stream = new FileStream(infoFile, FileMode.OpenOrCreate);

            ser.Serialize(stream, info);

            stream.Close();
        }

        public static SettingInfo GetSettingInfo()
        {
            if (!File.Exists(infoFile))
                return CreateNewsInfoFile();

            FileStream stream = new FileStream(infoFile, FileMode.OpenOrCreate);

            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(SettingInfo));
                return (SettingInfo)ser.Deserialize(stream);
            }
            catch
            {
                stream.Close();
                if (File.Exists(infoFile))
                    File.Delete(infoFile);
                return CreateNewsInfoFile();
            }
            finally
            {
                stream.Close();
            }
        }

        private static SettingInfo CreateNewsInfoFile()
        {
            SettingInfo info = new SettingInfo();
            info.LastGetTime = DateTime.Now;
            info.LastUpdateTime = DateTime.Now;
            info.UrlAddress = "http://192.168.0.189/schedule.csv";
            info.UserName = "";
            info.RefreshTime = 10;

            SettingInfoHelper.SaveInfo(info);
            return info;
        }
    }
}
